<template>
  <div>
    <el-descriptions class="margin-top" :column="1" border>
      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['icon']?.required ? 'required' : ''">
            <span>{{ t(formKeys["icon"].label) }}</span>
          </div>
        </template>
        <el-upload
          :show-file-list="false"
          class="upload-empDocs"
          action="/autata/file/upload"
          accept="image/*"
          :data="{ foldername: 'formula' }"
          @success="e => onSuccess(e)"
        >
          <img
            v-if="baseInfo[formKeys['icon'].key]"
            :src="
              handleImgURL(baseInfo[formKeys['icon'].key]) +
              baseInfo[formKeys['icon'].key]
            "
            class="h-full"
            :alt="t('formula_detail.icon')"
          />
          <div v-else class="text-center">
            <FontIcon icon="icon-upload" />
            {{ t("formula_detail.icon_upload") }}
          </div>

          <div class="close" @click="remove($event, formKeys['icon'].key)">
            <IconifyIconOffline icon="ep:close" />
          </div>
        </el-upload>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['name']?.required ? 'required' : ''">
            <span>{{ t(formKeys["name"].label) }}</span>
          </div>
        </template>
        <el-input
          v-model="baseInfo[formKeys['name'].key]"
          class="!w-[200px]"
          maxlength="30"
          :placeholder="`${t('formula_detail.please_input')}${t(formKeys['name'].label)}`"
        />
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['tag_list']?.required ? 'required' : ''">
            <span>{{ t(formKeys["tag_list"].label) }}</span>
          </div>
        </template>
        <div class="flex justify-start tag-au-select">
          <AuSelect
            v-model="baseInfo[formKeys['tag_list'].key]"
            style="width: 400px"
            :placeholder="`${t('formula_detail.please_select')}${t(formKeys['tag_list'].label)}`"
            valueKey="id"
            labelKey="name"
            :options="tagOptions"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :max-collapse-tags="3"
            @change="tagChange"
          />
          <el-button
            link
            type="primary"
            size="small"
            @click="showTagModal = true"
          >
            <FontIcon icon="icon-plus" />
            &nbsp;{{ t("formula_detail.add_tag") }}
          </el-button>
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div
            :class="formKeys['specification_list']?.required ? 'required' : ''"
          >
            <span>{{ t(formKeys["specification_list"].label) }}</span>
          </div>
        </template>
        <el-button
          class="add-btn !w-auto"
          color="#F5F9FF"
          size="small"
          @click="addSpec"
        >
          <FontIcon icon="icon-plus2" />
          &nbsp;{{ t("formula_detail.add_spec") }}
        </el-button>

        <div
          v-for="item in specList"
          :key="item.id"
          class="bg-[--autata-bg-normal-color] flex py-2 px-4 items-center mt-2"
        >
          <div class="w-[100px]">{{ item.name }}</div>
          <div class="flex flex-wrap gap-2 w-[50vw]">
            <div
              v-for="attr in item.attr"
              :key="attr.name"
              :class="['spec-box', attr.checked ? 'active' : '']"
              @click="attrCheck(attr)"
            >
              {{ attr.name }}
            </div>
          </div>
          <div class="ml-auto">
            <el-button
              link
              class="!text-[#EA2626] !text-[12px] !hover:text-[#ea4949]"
              @click="removeSpec(item.id)"
            >
              <component
                :is="useRenderIcon(Delete)"
                class="text-[12px] ml-1 mt-[1px]"
              />
              <span class="inline-block align-middle"
                >&nbsp;{{ t("buttons.delete") }}</span
              >
            </el-button>
          </div>
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['third_value']?.required ? 'required' : ''">
            <span>{{ t(formKeys["third_value"].label) }}</span>
          </div>
        </template>
        <div class="flex items-center">
          <el-input
            v-model="baseInfo[formKeys['third_value'].key]"
            class="!w-[200px]"
            maxlength="30"
            :placeholder="`${t('formula_detail.please_input')}${t(formKeys['third_value'].label)}`"
          />
          <el-checkbox
            v-model="baseInfo.is_effective"
            true-value="1"
            false-value="0"
            class="ml-2"
          >
            <span class="text-[12px]">{{
              t("formula_detail.is_priority")
            }}</span>
          </el-checkbox>
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['note']?.required ? 'required' : ''">
            <span>{{ t(formKeys["note"].label) }}</span>
          </div>
        </template>
        <div class="flex items-center">
          <el-input
            v-model="baseInfo[formKeys['note'].key]"
            type="textarea"
            class="!w-[400px]"
            :rows="3"
            maxlength="200"
            :placeholder="t('formula_detail.note_placeholder')"
          />
        </div>
      </el-descriptions-item>

      <el-descriptions-item>
        <template #label>
          <div :class="formKeys['publish_status']?.required ? 'required' : ''">
            <span>{{ t(formKeys["publish_status"].label) }}</span>
          </div>
        </template>
        <el-radio-group v-model="baseInfo[formKeys['publish_status'].key]">
          <el-radio value="1">{{ t("formula_detail.sold_out") }}</el-radio>
          <el-radio value="0">{{ t("formula_detail.putaway") }}</el-radio>
        </el-radio-group>
      </el-descriptions-item>
    </el-descriptions>
    <TagEditModal
      v-model="showTagModal"
      :formData="{}"
      @confirm="tagListHandle"
    />
  </div>
</template>

<script setup lang="ts">
import {
  getCurrentInstance,
  nextTick,
  onBeforeMount,
  onMounted,
  ref,
  watch
} from "vue";
import { handleImgURL } from "@/utils/tool";
import { ResultProps } from "@/api/user";
import { AuSelect } from "@/components/AuForm";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Delete from "@/assets/svg/delete.svg?component";
import { getTagList, SpecificationList } from "@/api/cabinet/formulaDetail";
import TagEditModal from "./TagEditModal.vue";
import { getSpecificationList } from "@/api/cabinet/specification";
import { isArray, isString } from "@pureadmin/utils";
import { cloneDeep } from "lodash-unified";
import { useI18n } from "vue-i18n";

const { t } = useI18n();

const props = defineProps<{
  baseData: { [key: string]: PropertyKey };
  specCheckList: any[];
}>();
const emits = defineEmits(["pageBefore", "specChange"]);

const { proxy } = getCurrentInstance();
const baseInfo = ref({
  icon: "", // 配方主图
  name: "", // 配方名称
  tag_list: [], // 配方标签
  tag: [], // 配方标签
  third_value: "", // 外部ID
  note: "", // 备注
  publish_status: "1",
  is_effective: "0"

  // formula_subid: "",
  // formula_version: "",
  // material_list: "",
  // formula_detail: "",
  // version: ""
});

const formKeys = ref({
  icon: {
    label: "formula_detail.icon",
    key: "icon",
    required: false
  },
  name: {
    label: "formula_detail.name",
    key: "name",
    required: true
  },
  tag_list: {
    label: "formula_detail.tag_list",
    key: "tag",
    required: true
  },
  specification_list: {
    label: "formula_detail.specification_list",
    key: "specification_list",
    required: true
  },
  third_value: {
    label: "formula_detail.third_value",
    key: "third_value",
    required: false
  },
  note: {
    label: "table.note",
    key: "note",
    required: false
  },
  publish_status: {
    label: "formula_detail.publish_status",
    key: "publish_status",
    required: true
  }
});
const tagOptions = ref([]);
const showTagModal = ref(false);

const specList = ref([]);
const specOriginList = ref([]);

// region -----------------------------事件功能集合-----------------------------
const onSuccess = (
  rawFile: ResultProps<{
    path: string;
    relative_path: string;
    size: number;
  }>
) => {
  baseInfo.value.icon = rawFile.data.relative_path;
};

const remove = (e: MouseEvent, key: string) => {
  e.stopPropagation();
  baseInfo.value[key] = "";
};

const attrCheck = (attr: any) => {
  attr.checked = !attr.checked;
  emits("specChange", specList.value);
};

// endregion

// region -----------------------------通用功能集合-----------------------------

const tagListHandle = async () => {
  const res = await getTagList({ size: 0 });
  tagOptions.value = res.data;
};

const tagChange = (val: string[]) => {
  if (isArray(val)) {
    baseInfo.value.tag_list = tagOptions.value
      .filter(item => val.includes(item.id))
      .map(v => ({ id: v.id, name: v.name }));
  }
};

const getSpecList = async () => {
  const res = await getSpecificationList({ size: 0 });
  specOriginList.value = res.data;
  if (isString(proxy.$route.query.specIds)) {
    const specIds = JSON.parse(proxy.$route.query.specIds);
    console.log("specList.value", specList.value);
    const cloneSpec = cloneDeep(specList.value);
    await nextTick(() => {
      specList.value = [];
      specOriginList.value
        .filter(item => specIds.includes(item.id))
        .forEach(v => {
          const find = cloneSpec.find(h => h.id === v.id);
          if (find) {
            specList.value.push(find);
          } else {
            const spec = {
              ...v,
              attr: v.attr.split(",").map(h => ({ name: h, checked: true }))
            };
            specList.value.push(spec);
          }
        });
      emits("specChange", specList.value);
    });
  }
};

const setSpecList = (list: SpecificationList[]) => {
  const selfList = [];
  list.forEach(item => {
    const spec = {};
    spec["id"] = item.specification_id;
    spec["name"] = item.specification_name;
    const checkList = item.check_attr.split(",");
    spec["attr"] = item.specification_attr
      .split(",")
      .map(h => ({ name: h, checked: checkList.includes(h) }));
    selfList.push(spec);
  });
  specList.value = selfList;

  emits("specChange", specList.value);
};

// endregion

const addSpec = () => {
  emits("pageBefore");
  proxy.$router.push({
    name: "CabinetSpecification",
    query: {
      ...proxy.$route.query,
      specIds: JSON.stringify(specList.value.map(v => v.id))
    }
  });
};
const removeSpec = (id: number) => {
  const index = specList.value.findIndex(item => item.id === id);
  specList.value.splice(index, 1);
  emits("specChange", specList.value);
};

const validate = () => {
  for (const key in formKeys.value) {
    const item = formKeys.value[key];
    if (item.required && key !== "specification_list") {
      if (
        baseInfo.value[key] === "" ||
        (isArray(baseInfo.value[key]) && !baseInfo.value[key].length)
      ) {
        proxy.$auMessageBox.alert(t(item.label) + "不能为空", "提示");
        return false;
      }
    }
  }

  if (!specList.value.length) {
    proxy.$auMessageBox.alert(
      t("formula_detail.select_specification"),
      t("notice.title")
    );
    return false;
  } else {
    let checkNum = 0;
    specList.value.forEach(item => {
      item.attr.forEach(attr => {
        if (attr.checked) {
          checkNum++;
        }
      });
    });
    if (checkNum === 0) {
      proxy.$auMessageBox.alert(
        t("formula_detail.select_specification_prop"),
        t("notice.title")
      );
      return false;
    }
  }
  return true;
};

onBeforeMount(() => {
  tagListHandle();
  getSpecList();
});

const getBaseInfo = () => {
  const baseInfoData = {};
  for (const key in baseInfo.value) {
    baseInfoData[key] = isString(baseInfo.value[key])
      ? baseInfo.value[key].trim()
      : baseInfo.value[key];
  }
  return baseInfoData;
};

defineExpose({
  getBaseInfo,
  getSpecList: () => specList.value,
  setSpecList,
  validate
});

watch(
  () => props.baseData,
  val => {
    if (val) {
      for (const valKey in val) {
        baseInfo.value[valKey] = val[valKey];
        if (valKey === "publish_status") {
          baseInfo.value[valKey] = String(val[valKey]);
        }
      }
    }
  },
  {
    immediate: true
  }
);

watch(
  () => props.specCheckList,
  val => {
    specList.value = val;
    getSpecList();
  },
  {
    immediate: true
  }
);
</script>

<style lang="scss">
.spec-box {
  width: 108px;
  height: 38px;
  font-size: 14px;
  line-height: 38px;
  color: var(--autata-font-color);
  text-align: center;
  cursor: pointer;
  background-color: var(--autata-bg-color);
  border: 1px solid transparent;
  border-radius: var(--autata-border-radius-px);
  transition: all 0.3s ease-in-out;

  &:hover {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }

  &.active {
    color: var(--el-color-primary);
    border-color: var(--el-color-primary);
  }
}

.tag-au-select {
  .el-tag {
    font-weight: 500;
    color: var(--el-color-primary);
    background-color: var(--autata-bg-normal-color);

    .el-tag__close {
      color: var(--el-color-primary);
    }
  }
}

.required {
  span::before {
    display: inline-block;
    margin-right: 4px;
    color: var(--el-color-danger);
    content: "*";
  }
}
</style>
